﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO.Pipes;
using System.Text;
using System.Xml;


[System.Runtime.CompilerServices.CompilerGenerated]
public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlBinary Encrypt(SqlString input)
    {
        if (input.IsNull || string.IsNullOrEmpty(input.Value))
            return SqlBinary.Null;

        using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "OsmEncryptionPipe", PipeDirection.InOut))
        {
            pipeClient.Connect(5000);
            WriteToPipe(pipeClient, "<Encrypt><![CDATA[" + input.Value + "]]></Encrypt>");
            using (XmlReader rdr = XmlReader.Create(pipeClient))
            {
                rdr.Read();

                if (rdr.IsStartElement())
                {
                    switch (rdr.Name)
                    {
                        case "data":
                            return new SqlBinary(Convert.FromBase64String(rdr.ReadString()));
                        case "error":
                            throw new Exception(rdr.ReadString());
                    }
                }
            }
        }
        throw new Exception("Unknown error in Encrypt");
    }

    [Microsoft.SqlServer.Server.SqlFunction(DataAccess=DataAccessKind.Read)]
    public static SqlString Decrypt(SqlBinary input)
    {
        if (input.IsNull || input.Length == 0)
            return SqlString.Null;

        using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "OsmEncryptionPipe", PipeDirection.InOut))
        {
            pipeClient.Connect(5000);
            WriteToPipe(pipeClient, "<Decrypt><![CDATA[" + Convert.ToBase64String(input.Value) + "]]></Decrypt>");
            using (XmlReader rdr = XmlReader.Create(pipeClient))
            {
                rdr.Read();

                if (rdr.IsStartElement())
                {
                    switch (rdr.Name)
                    {
                        case "data":
                            return new SqlString(rdr.ReadString());
                        case "error":
                            throw new Exception(rdr.ReadString());
                    }
                }
            }
        }
        throw new Exception("Unknown error in Decrypt");
    }

    private static void WriteToPipe(NamedPipeClientStream pipeClient, string value)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(value);
        pipeClient.Write(buffer, 0, buffer.Length);
    }
};
